// https://leetcode.cn/problems/rotting-oranges/description/?envType=study-plan-v2&envId=top-100-liked

#include <iostream>
using namespace std;

#include <queue>
#include <vector>
#include <algorithm>

class Solution 
{
public:
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    typedef pair<int, int> PII;

    int orangesRotting(vector<vector<int>>& grid) 
    {
        int m = grid.size(), n = grid[0].size();

        int news = 0;

        queue<PII> q;
        for (int i = 0 ; i < m ; i++)
        {
            for (int j = 0 ; j < n ; j++)
            {
                if (grid[i][j] == 0)
                {
                    continue;
                }
                else if (grid[i][j] == 1)
                {
                    news++;
                }
                else
                {
                    q.push({i, j});
                }
            }
        }

        int ret = 0;
        while (!q.empty())
        {
            int sz = q.size();
            if (news == 0) break;
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();

                for (int i = 0 ; i < 4 ; i++)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 1)
                    {
                        news--;
                        grid[x][y] = 2;
                        q.push({x, y});
                    }
                }
            }
            ret++;
        }

        return news == 0 ? ret : -1;
    }
};

int main()
{
    vector<vector<int>> grid1 = {{2,1,1},{1,1,0},{0,1,1}};
    vector<vector<int>> grid2 = {{2,1,1},{0,1,1},{1,0,1}};
    Solution sol;

    cout << sol.orangesRotting(grid1) << endl;
    cout << sol.orangesRotting(grid2) << endl;

    return 0;
}